package com.wsd.smartcarwasher.controller;

import com.wsd.smartcarwasher.configuration.mqtt.MqttGateway;
import com.wsd.smartcarwasher.constans.Constant;
import com.wsd.smartcarwasher.util.ReturnUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;


@RestController
public class MessageMqttController {

    private static final Logger logger = LoggerFactory.getLogger(MessageMqttController.class);

    @Autowired
    MqttGateway mqttGateway;

    @RequestMapping(value = "/v1/sendMsg", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap sendMsg(@RequestParam String message){

        try {
            mqttGateway.sendToMqtt("defualt-topic:"+message);
        }catch (Exception e) {
            logger.error("sendMessage fail: " + e.getMessage());
            return ReturnUtil.Error(e.getMessage());
        }
        return ReturnUtil.Success("ok");
    }

    /**
     * 暂停设备运行
     * @param clientID 机器码
     * @return
     */
    @RequestMapping(value = "/v1/sendStopMsg", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap sendStopMsg(@RequestParam("clientID") String clientID, @RequestBody String msg){

        try {
            mqttGateway.sendToMqtt(clientID, 1, msg);
        }catch (Exception e) {
            logger.error("sendMessage fail: " + e.getMessage());
            return ReturnUtil.Error(e.getMessage());
        }
        return ReturnUtil.Success("ok");
    }


    /**
     * 暂停开始运行
     * @param clientID 机器码
     * @return
     */
    @RequestMapping(value = "/v1/sendStartMsg", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap sendStartMsg(@RequestParam String clientID){

        try {
            mqttGateway.sendToMqtt(clientID, 1, String.valueOf(Constant.START_FLAG));
        }catch (Exception e) {
            logger.error("sendMessage fail: " + e.getMessage());
            return ReturnUtil.Error(e.getMessage());
        }
        return ReturnUtil.Success("ok");
    }
}
